package com.shujia

import scala.io.{BufferedSource, Source}

object Demo24WordCount {
  def main(args: Array[String]): Unit = {
    //1、读取数据
    val bufferedSource: BufferedSource = Source.fromFile("scala/data/words.txt")
    val lines: List[String] = bufferedSource.getLines().toList

    //2、将一行中的多个单词转换多行
    val words: List[String] = lines.flatMap((line: String) => line.split(","))

    //3、按照单词进行分组
    val groupBy: Map[String, List[String]] = words.groupBy((word: String) => word)

    //4、统计单词的数量
    val wordCount: Map[String, Int] = groupBy.map(kv => {
      val word: String = kv._1
      val list: List[String] = kv._2
      //计算单词的数量
      val count: Int = list.length
      //返回一个元组
      (word, count)
    })
    wordCount.foreach(println)
  }

}
